package com.example.index.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.index.mapper.CollectMapper;
import com.example.index.mapper.HouseMapper;
import com.example.index.service.HouseService;
import com.example.index.service.ImageService;
import com.example.index.service.impl.HouseServiceImpl;
import com.yc.pojo.*;
import com.yc.pojo.House;
import com.yc.pojo.HouseDTO;
import com.yc.pojo.Image;
import com.yc.util.Utils;
import com.yc.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.net.URL;
import java.util.Map;


@RestController
@RequestMapping("house")
public class HouseController {
    public static String URL = "https://api.map.baidu.com/geocoding/v3?";
    public static String AK = "YSTdjtYERsneLAtwY6qA8IkMpOeHzfPa";
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private HouseServiceImpl houseServiceImpl;

    @Resource
    private HouseService houseService;

    @Resource
    private ImageService imageService;

    @Resource
    private HouseMapper houseMapper;

    @Resource
    private CollectMapper collectMapper;

    @GetMapping("getCount")
    public Result getCount(){
        String s2= LocalDateTime.now().toString().substring(0, 8);
        String s = LocalDateTime.now().toString().substring(8, 10);
        List<Integer> list=new ArrayList<>();
        List<String> list2=new ArrayList<>();
        List<String> list3=new ArrayList<>();
        Map<String,Integer> map=new HashMap<>();
        int i= Integer.parseInt(s);
        if (i-7>0){
            for (int j = 6; j >=0; j--) {
                list.add((i-j));
            }
        }
        for (Integer s1 : list) {
            if (s1<10){
                list2.add(s2+"0"+s1);
            }
        }
        for (String s1 : list2) {
            Long size = redisTemplate.opsForSet().size(s1);
            if (size==null){
                size= Long.valueOf(0);
            }
            list3.add(String.valueOf(Math.toIntExact(size)));
        }
        list2.addAll(list3);
        StringBuilder stringBuilder=new StringBuilder();
        for (String s1 : list2) {
            stringBuilder.append(s1).append(",");
        }
        return Result.success("success",stringBuilder);
    }

    //主页房源渲染
    @RequestMapping("select")
    public List select(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "5") Integer size,
                       String province, String city, String region, String rent, String room, String type){
        LambdaQueryWrapper<House> lqw = new LambdaQueryWrapper<>();
        if (province.equals("全部") == false){
            lqw.eq(House::getProvince, province);
        }
        if (city.equals("全部") == false){
            lqw.eq(House::getCity, city);
        }
        if (region.equals("全部") == false){
            lqw.eq(House::getRegion, region);
        }
        if (rent.equals("全部") == false){
            System.out.println("rent.contains('-') = " + rent.contains("-"));
            if (rent.contains("-")){
                final String[] split = rent.split("-");
                String minPrice = split[0];
                String maxPrice = split[1].replaceAll("[\\D]+", "");
                lqw.between(House::getPrice,minPrice,maxPrice);
            }else{
                String price = rent.replaceAll("[\\D]+", "");
                if (rent.contains("上")){
                    lqw.gt(House::getPrice, price);
                } else if (rent.contains("下")){
                    lqw.lt(House::getPrice, price);
                }
            }
        }
        if (room.equals("全部") == false){
            if (room.equals("五室及以上")){
                lqw.notLike(House::getScale, "1室")
                        .notLike(House::getScale, "2室")
                        .notLike(House::getScale, "3室")
                        .notLike(House::getScale, "4室");
            } else {
                if (room.equals("一室")){
                    room = "1室";
                } else if (room.equals("二室")){
                    room = "2室";
                } else if (room.equals("三室")){
                    room = "3室";
                } else if (room.equals("四室")){
                    room = "4室";
                }
                lqw.like(House::getScale, room);
            }
        }
        if (type.equals("全部") == false){
            lqw.eq(House::getType, type);
        }
        lqw.orderByDesc(House::getId);
        final List<House> list = list(houseMapper.selectPage(new Page<>(page, size), lqw).getRecords());
        return list;
    }

    public List list(List<House> list){
        List<House> houseList = new ArrayList<>();
        for (House house : list) {
            house.setImage(image(house.getId()));
            houseList.add(house);
        }
        return houseList;
    }
    //主页房源图片获取-----取第一张
    @GetMapping("image")
    public String image(int groupId){
        LambdaQueryWrapper<Image> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Image::getGroupId,groupId);
        List<Image> list = imageService.list(queryWrapper);
        String imageUrl = list.get(0).getUrl();
        return imageUrl;
    }

    @RequestMapping("get")
    public List get(){
        List<House> list = houseService.page(new Page<>(1, 10)).getRecords();
        List<HouseDTO> houseDTOList= list.stream().map(res->{
            String imageUrl = image(res.getId());
            HouseDTO houseDTO = new HouseDTO();
            houseDTO.setImgUrls(Collections.singletonList(imageUrl));
            BeanUtils.copyProperties(res,houseDTO);
            return houseDTO;
        }).collect(Collectors.toList());
        return houseDTOList;
    }


    //房源详情信息获取
    @GetMapping("details") //传入房源id
    public Result images(Integer houseId, Integer userId) throws Exception {
        //根据id获取house对象和image图片信息，赋值给DTO，返回给前端
        LambdaQueryWrapper<Image> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Image::getGroupId,houseId);
        List<Image> list = imageService.list(queryWrapper);
        List<String> imgUrls=list.stream().map(res-> res.getUrl()).collect(Collectors.toList());
        House house = houseService.getById(houseId);
        HouseDTO houseDTO = new HouseDTO();
        BeanUtils.copyProperties(house,houseDTO);
        houseDTO.setImgUrls(imgUrls);
        LambdaQueryWrapper<Collect> lqw = null;
        if (userId != null){
            lqw = new LambdaQueryWrapper<>();
            lqw.eq(Collect::getHouseId, houseId).eq(Collect::getUserId,userId);
            SetOperations set = redisTemplate.opsForSet();
            //总访问量
            set.add(LocalDateTime.now().toString().substring(0,10),userId+"with"+houseId);
            //每个用户名下房源的访问量
            //set.add(house.getMasterId()+"-"+LocalDateTime.now().toString().substring(0,10),userId+"with"+houseId);
        }
        boolean isCollect = false;
        Collect collect = null;
        if (lqw != null){
            collect = collectMapper.selectOne(lqw);
        }
        if (collect != null){
            isCollect = true;
        }
        //获取地址参数
        LambdaQueryWrapper<House> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.between(House::getLng,houseDTO.getLng()-0.05,houseDTO.getLng()+0.05);
        queryWrapper1.between(House::getLat,houseDTO.getLat()-0.05,houseDTO.getLat()+0.05);
        //queryWrapper1.ne(House::getLng,houseDTO.getLng());
        List<House> list1 = houseService.list(queryWrapper1);
        houseDTO.setNearbyHouseList(list1);

        Map<String, Object> map = new HashMap<>();
        map.put("house",houseDTO);
        map.put("isCollect", isCollect);
        return Result.success("success",map);
    }

    //添加或修改房源
    @PostMapping("save")
    @Transactional
    public Result save(@RequestBody @Valid HouseDTO houseDto, Errors errors) throws Exception {
        if (errors.hasErrors()){
          return Result.failure("房源提交数据错误",errors.getAllErrors());
        }
        Map params = new LinkedHashMap<String, String>();
        //输入地址获取经纬度
        params.put("address",houseDto.getProvince()+houseDto.getCity()+houseDto.getRegion()+houseDto.getAddress());
        params.put("output", "json");
        params.put("ak", AK);
        //获取经纬度，逗号分割 如112.23413231,28.23414213
        final String[] split = this.requestGetAK(URL, params).split(",");
        houseDto.setLng(Double.parseDouble(split[0]));
        houseDto.setLat(Double.parseDouble(split[1]));

        House house = new House();
        //拷贝houseDto中的属性到house
        BeanUtils.copyProperties(houseDto,house);
        houseService.saveOrUpdate(house);
        if (houseDto.getImgUrls()==null){
            return Result.success("success");
        }
        Integer id = house.getId();
        List<Image> images1=new ArrayList<>();
        for (String image : houseDto.getImgUrls()) {
            Image image1 = new Image();
            image1.setGroupId(id);
            image1.setUrl(image);
            images1.add(image1);
        }
        imageService.saveOrUpdateBatch(images1);
        return Result.success("房源发布成功!");
    }

    //删除
    @GetMapping("delete")
    @Transactional
    public Result delete(int id){
        boolean remove = houseService.removeById(id);
        LambdaQueryWrapper<Image> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Image::getGroupId,id);
        boolean remove1 = imageService.remove(queryWrapper);
        if (remove&&remove1)
            return Result.success("删除成功");
        else
            return Result.failure("删除失败");
    }

    //修改房源时回显
    @GetMapping("update") //传入房源id
    public Result update(Integer id){
        House house = houseService.getById(6); //默认为6
        LambdaQueryWrapper<Image> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Image::getGroupId,6);
        List<Image> list = imageService.list(queryWrapper);
        List<String> imgUrls=list.stream().map(res-> res.getUrl()).collect(Collectors.toList());
        HouseDTO houseDTO = new HouseDTO();
        BeanUtils.copyProperties(house,houseDTO);
        houseDTO.setImgUrls(imgUrls);
        return Result.success("修改成功",houseDTO);
    }

    //获取个人主页房源信息
    @RequestMapping("master")
    public Result getByMasterId(Integer userId,int page,int pageSize){
        Page<House> pages=new Page<>(page,pageSize);
        LambdaQueryWrapper<House> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(House::getMasterId,userId);
        houseService.page(pages,queryWrapper);

        //获取图片
        pages.setRecords(pages.getRecords().stream().map(item->{
            item.setImage(image(item.getId()));
            return item;
        }).collect(Collectors.toList()));
        return Result.success("success",pages);
    }

    //后台房源管理数据获取
    @GetMapping("background")
    public Result getBackground(Integer id,Integer guestId,String value,int page,int pageSize){
        LambdaQueryWrapper<House> queryWrapper=new LambdaQueryWrapper<>();
        if (!Utils.isEmpty(id)){
            queryWrapper.eq(House::getId,id);
        }
        if (!Utils.isEmpty(guestId)){
            queryWrapper.eq(House::getGuestId,guestId);
        }
        if (!Utils.isEmpty(value)){
            String[] split = value.split(",");
            queryWrapper.between(House::getPrice,split[0],split[1]);
        }
        Page<House> pages=new Page<>(page,pageSize);
        houseService.page(pages,queryWrapper);
        return Result.success("success",pages);
    }
	
	//地图查询 范围内的所有房子的经纬度
    @RequestMapping("getHouse")
    public Result getHouse( String swlatitude,String swlongitude,String nelatitude ,String nelongitude){
        List<House> house = houseServiceImpl.getHouse(swlatitude, swlongitude, nelatitude, nelongitude);
        if (house.size() != 0){
            return Result.success("查询成功",house);
        }else {
            return Result.failure("查询失败");
        }
    }

    public String requestGetAK(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return null;
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            queryString.append(URLEncoder.encode((String) pair.getValue(),
                    "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        String path=buffer.toString();
        int i=path.indexOf("g");
        int i1=path.indexOf(",",i);
        int i2=path.indexOf(":",i1);
        int i3=path.indexOf("}",i2);
        return path.substring(i+3,i1)+","+path.substring(i2+1,i3);
    }

    /**
     * 根据code获取唯一opennid
     * @param code
     * @return
     */
    @PostMapping("wx/getCode")
    public Result WxLogin( String code){
        System.out.println(code);
        Map<String, Object> map = houseServiceImpl.getCode(code);

        return Result.success("success", map);
    }

    @GetMapping("wx/getAccessToken")
    public Result GetAccessToken(){
        String accessToken = houseServiceImpl.getAccessToken();
        return Result.success("success", accessToken);
    }

    @PostMapping("wx/getphone")
    public Result getPhone(@RequestParam("access_token") String access_token,@RequestBody String code){
        String phoneNumber = houseServiceImpl.getPhoneNumber(access_token,code);
        return Result.success("success", phoneNumber);
    }
}
